﻿using CommunityToolkit.Mvvm.Input;
using ControlzEx.Theming;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using Notifications.Wpf;
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using VideoTools.Extension;
using VideoTools.vo;

namespace VideoTools.Commands
{
    public class MainWindowCommands : NotifyPropertyBase, IDisposable
    {
        private static volatile MainWindowCommands _instance;
        private static readonly object SyncRoot = new object();
        public CustomDialog dialog = null;

        public static MainWindowCommands Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new MainWindowCommands();
                        }
                    }
                }

                return _instance;
            }
        }

        private MainWindowCommands() { }

        private volatile bool _isDisposed;

        public void Dispose()
        {
            if (_isDisposed)
                return;

            _isDisposed = true;
        }

        private ObservableCollection<string> _Notifycations = new ObservableCollection<string>();
        public ObservableCollection<string> Notifycations
        {
            get => _Notifycations;
            set => SetProperty(ref _Notifycations, value);
        }

        private ICommand _ExportJianYingDraftCommand;
        private ICommand _ShowJianYingMenuCommand;
        private ICommand _OpenJianYingOutPathCommand;
        private ICommand _ExportJianYingAudioOrVideoCommand;
        private ICommand _ExportJianYingVideoRenameCommand;
        private ICommand _ConfigJianYingDraftCommand;
        private ICommand _ConfigJianYingOutCommand;
        private ICommand _OpenJianYingDraftPathCommand;
        private ICommand _JianYingHelpCommand;

        private ICommand _SetDefaultPageCommand;
        private ICommand _SetVideoPlayerCommand;
        private ICommand _ShowMenuCommand;
        private ICommand _ShowPageCommand;
        private ICommand _OpenGitAddressCommand;
        private ICommand _ChangeAccentColorCommand;
        private ICommand _ChangeBackgroundCommand;
        private ICommand _ShowSettingsCommand;
        private ICommand _CopyThemeColorCommand;
        private ICommand _CloseDialogCommand;

        public ICommand CloseDialogCommand =>
            _CloseDialogCommand
            ?? (
                _CloseDialogCommand = new RelayCommand<object>(o =>
                {
                    if (dialog != null)
                    {
                        MainWindow.Instance.HideMetroDialogAsync(dialog);
                        dialog = null;
                    }
                })
            );
        public ICommand CopyThemeColorCommand =>
            _CopyThemeColorCommand
            ?? (
                _CopyThemeColorCommand = new RelayCommand<object>(o =>
                {
                    try
                    {
                        System.Windows.Clipboard.SetText(o.ToString());
                    }
                    catch (Exception es) { }
                })
            );
        public ICommand ShowSettingsCommand =>
            _ShowSettingsCommand
            ?? (
                _ShowSettingsCommand = new RelayCommand<object>(o =>
                {
                    if (
                        System.Windows.Application.Current.MainWindow != null
                        && AppManager.Instance.ThemeColors.Count == 0
                    )
                    {
                        InitThemeColor();
                    }
                    MainWindowCommands.Instance.dialog = new CustomDialog(
                        MainWindow.Instance.MetroDialogOptions
                    )
                    {
                        Content = o,
                        Title = "设置",
                        Style = (Style)
                            System.Windows.Application.Current.Resources["CustomDialogStyle"], // 应用样式
                    };
                    MainWindow.Instance.ShowMetroDialogAsync(MainWindowCommands.Instance.dialog);
                    //AppManager.Instance.SettingsFlyoutOpened = true;
                })
            );

        private void InitThemeColor()
        {
            var theme = ThemeManager.Current.DetectTheme(
                System.Windows.Application.Current.MainWindow
            );
            if (theme is not null)
            {
                AppManager.Instance.ThemeColors.Clear();
                var libraryTheme = theme.LibraryThemes.FirstOrDefault(x =>
                    x.Origin == "MahApps.Metro"
                );
                var resourceDictionary =
                    libraryTheme?.Resources.MergedDictionaries.FirstOrDefault();

                if (resourceDictionary != null)
                {
                    foreach (var dictionaryEntry in resourceDictionary.OfType<DictionaryEntry>())
                    {
                        string key = dictionaryEntry.Key.ToString();
                        object? value = dictionaryEntry.Value;

                        vo.ThemeColor tc = new vo.ThemeColor(key, value);
                        AppManager.Instance.ThemeColors.Add(tc);
                    }
                }
            }
        }

        public ICommand SetVideoPlayerCommand =>
            _SetVideoPlayerCommand
            ?? (
                _SetVideoPlayerCommand = new RelayCommand<object>(o =>
                {
                    System.Windows.Forms.OpenFileDialog openFileDialog =
                        new System.Windows.Forms.OpenFileDialog();
                    string filter = "(*.exe)|*.exe";
                    openFileDialog.Filter = filter;
                    openFileDialog.Multiselect = false;
                    openFileDialog.Title = "设置默认的视频播放器";
                    openFileDialog.RestoreDirectory = true;
                    openFileDialog.FilterIndex = 1;
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string file = openFileDialog.FileName;
                        AppConfig.Instance.VideoPlayerPath = file;
                        AppConfig.Instance.Save();
                    }
                    else
                    {
                        return;
                    }
                })
            );
        public ICommand ShowJianYingMenuCommand =>
            _ShowJianYingMenuCommand
            ?? (
                _ShowJianYingMenuCommand = new RelayCommand<object>(o =>
                {
                    if (string.IsNullOrEmpty(AppConfig.Instance.JianYingDraftPath))
                    {
                        ConfigJianYingDraftCommand.ExecuteIfCan();
                    }
                    if (string.IsNullOrEmpty(AppConfig.Instance.JianYingOutPath))
                    {
                        ConfigJianYingOutCommand.ExecuteIfCan();
                    }
                    System.Windows.Controls.Button button = (System.Windows.Controls.Button)o;
                    if (button.ContextMenu != null)
                    {
                        button.ContextMenu.PlacementTarget = button;
                        button.ContextMenu.Placement = PlacementMode.Bottom;
                        button.ContextMenu.IsOpen = true;
                    }

                    MainWindow window = MainWindow.Instance;
                    MenuItem audioMenuItem = window.JianYingAudioMenuItem();
                    MenuItem videoMenuItem = window.JianYingVideoMenuItem();
                    MenuItem videoRenameMenuItem = window.JianYingVideoRenameMenuItem();
                    audioMenuItem.Items.Clear();
                    videoMenuItem.Items.Clear();
                    videoRenameMenuItem.Items.Clear();
                    DirectoryInfo dir = new DirectoryInfo(AppConfig.Instance.JianYingDraftPath);
                    //获取当前目录JPG文件列表 GetFiles获取指定目录中文件的名称(包括其路径)
                    DirectoryInfo[] directoryInfos = dir.GetDirectories();
                    List<string> covers = new List<string>();
                    a:
                    foreach (DirectoryInfo sub in directoryInfos)
                    {
                        FileInfo[] files = sub.GetFiles();
                        if (files.Length == 0)
                        {
                            continue;
                        }
                        string fs = "";
                        foreach (FileInfo file in files)
                        {
                            fs += file.Name;
                        }
                        if (fs.Contains("draft_content.json") && fs.Contains("draft_cover.jpg"))
                        {
                            covers.Add(sub.Name);
                            string f = sub.GetFiles("draft_content.json")[0].FullName;
                            string content = File.ReadAllText(f);
                            JianYingDraft jydraft = JsonConvert.DeserializeObject<JianYingDraft>(
                                content
                            );
                            Dictionary<string, string> materialDict =
                                new Dictionary<string, string>();
                            foreach (Video v in jydraft.materials.videos)
                            {
                                materialDict.Add(v.id, v.path);
                            }
                            foreach (vo.Audio v in jydraft.materials.audios)
                            {
                                materialDict.Add(v.id, v.path);
                            }
                            foreach (vo.Track track in jydraft.tracks)
                            {
                                if (!track.type.Equals("video") && !track.type.Equals("audio"))
                                {
                                    continue;
                                }
                                foreach (Segment seg in track.segments)
                                {
                                    string material_id = seg.material_id;
                                    string path = null;
                                    materialDict.TryGetValue(material_id, out path);
                                    if (path == null || !File.Exists(path))
                                    {
                                        covers.Remove(sub.Name);
                                    }
                                }
                            }
                        }
                    }

                    for (int i = 0; i < covers.Count; i++)
                    {
                        string[] infos = covers[i].Split('\\');
                        string projectName = infos[infos.Length - 1];
                        System.Windows.Shapes.Path icon = null;
                        if (i < 98)
                        {
                            icon = (System.Windows.Shapes.Path)System.Windows.Application.Current.Resources["Icon_d" + (i + 1)]; 
                        }
                        MenuItem audioSubMenuItem = new MenuItem()
                        {
                            Header = projectName,
                            CommandParameter = "音频__" + projectName,
                            Icon = icon == null ? null : new System.Windows.Shapes.Path() { Data = icon.Data, Style = icon.Style, },
                            Command = MainWindowCommands.Instance.ExportJianYingAudioOrVideoCommand,
                        };
                        audioMenuItem.Items.Add(audioSubMenuItem);

                        MenuItem videoSubMenuItem = new MenuItem()
                        {
                            Header = projectName,
                            Icon = icon == null ? null : new System.Windows.Shapes.Path() { Data = icon.Data, Style = icon.Style, },
                            CommandParameter = "视频__" + projectName,
                            Command = MainWindowCommands.Instance.ExportJianYingAudioOrVideoCommand,
                        };
                        videoMenuItem.Items.Add(videoSubMenuItem);

                        MenuItem videoRenameSubMenuItem = new MenuItem()
                        {
                            Header = projectName,
                            Icon = icon == null ? null : new System.Windows.Shapes.Path() { Data = icon.Data, Style = icon.Style, },
                            CommandParameter = projectName,
                            Command = MainWindowCommands.Instance.ExportJianYingVideoRenameCommand,
                        };
                        videoRenameMenuItem.Items.Add(videoRenameSubMenuItem);

                        string content = File.ReadAllText(
                            AppConfig.Instance.JianYingDraftPath
                                + "\\"
                                + projectName
                                + "\\draft_content.json"
                        );
                        JianYingDraft jydraft = JsonConvert.DeserializeObject<JianYingDraft>(
                            content
                        );
                        Dictionary<string, string> materialDict = new Dictionary<string, string>();
                        foreach (Video v in jydraft.materials.videos)
                        {
                            materialDict.Add(v.id, v.path);
                        }
                        foreach (vo.Audio v in jydraft.materials.audios)
                        {
                            materialDict.Add(v.id, v.path);
                        }
                        List<Draft> drafts = new List<Draft>();
                        int trackIndex = 0;
                        foreach (vo.Track track in jydraft.tracks)
                        {
                            trackIndex++;
                            if (!track.type.Equals("video") && !track.type.Equals("audio"))
                            {
                                continue;
                            }
                            int segIndex = 0;
                            foreach (Segment seg in track.segments)
                            {
                                string material_id = seg.material_id;
                                string path = null;
                                materialDict.TryGetValue(material_id, out path);
                                materialDict.TryGetValue(material_id, out path);
                                Draft draft = new Draft();
                                draft.start = seg.source_timerange.start;
                                draft.duration = seg.source_timerange.duration;
                                draft.path = path;
                                draft.type = track.type.Equals(DraftType.audio.ToString())
                                    ? DraftType.audio
                                    : DraftType.video;
                                draft.index = segIndex;
                                draft.trackIndex = trackIndex;
                                drafts.Add(draft);
                                segIndex++;
                            }
                        }

                        for (int j = 0; j < drafts.Count; j++)
                        {
                            System.Windows.Shapes.Path icon1 = null;
                            if (j < 98)
                            {
                                icon1 = (System.Windows.Shapes.Path)System.Windows.Application.Current.Resources["Icon_d" + (j + 1)];
                            }
                            Draft draft = drafts[j];
                            MenuItem audioSubSubMenuItem = new MenuItem()
                            {
                                Header = "音频轨道_" + draft.trackIndex + "_" + draft.index,
                                CommandParameter =
                                    "音频_"
                                    + draft.trackIndex
                                    + "_"
                                    + draft.index
                                    + "---"
                                    + projectName,
                                Icon = icon1 == null ? null : new System.Windows.Shapes.Path() { Data = icon1.Data,Style = icon1.Style,},
                                Command = MainWindowCommands.Instance.ExportJianYingDraftCommand,
                            };
                            audioSubMenuItem.Items.Add(audioSubSubMenuItem);
                            if (draft.type == DraftType.video)
                            {
                                MenuItem videoSubSubMenuItem = new MenuItem()
                                {
                                    Header = "视频轨道_" + draft.trackIndex + "_" + draft.index,
                                    CommandParameter =
                                        "视频_"
                                        + draft.trackIndex
                                        + "_"
                                        + draft.index
                                        + "---"
                                        + projectName,
                                    Icon = icon1 == null ? null : new System.Windows.Shapes.Path() { Data = icon1.Data, Style = icon1.Style, },
                                    Command = MainWindowCommands
                                        .Instance
                                        .ExportJianYingDraftCommand,
                                };
                                videoSubMenuItem.Items.Add(videoSubSubMenuItem);
                            }
                        }
                    }
                })
            );
        public ICommand ExportJianYingDraftCommand =>
            _ExportJianYingDraftCommand
            ?? (
                _ExportJianYingDraftCommand = new RelayCommand<object>(o =>
                {
                    string p = (string)o;
                    bool isVideo = p.StartsWith("视频");

                    string[] infos = p.Split("_");
                    int clickTrackIndex = int.Parse(infos[1]);
                    infos = infos[2].Split("---");
                    int clickDraftIndex = int.Parse(infos[0]);
                    string project = infos[1];
                    string content = File.ReadAllText(
                        AppConfig.Instance.JianYingDraftPath
                            + "\\"
                            + project
                            + "\\draft_content.json"
                    );
                    JianYingDraft jydraft = JsonConvert.DeserializeObject<JianYingDraft>(content);
                    Dictionary<string, string> materialDict = new Dictionary<string, string>();
                    foreach (Video v in jydraft.materials.videos)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    foreach (vo.Audio v in jydraft.materials.audios)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    List<Draft> drafts = new List<Draft>();
                    int trackIndex = 0;
                    Draft draft = null;
                    foreach (vo.Track track in jydraft.tracks)
                    {
                        trackIndex++;
                        if (!track.type.Equals("video") && !track.type.Equals("audio"))
                        {
                            continue;
                        }
                        if (track.type.Equals("audio") && isVideo)
                        {
                            continue;
                        }
                        int segIndex = 0;
                        foreach (Segment seg in track.segments)
                        {
                            if (clickTrackIndex == trackIndex && segIndex == clickDraftIndex)
                            {
                                string material_id = seg.material_id;
                                string path = null;
                                materialDict.TryGetValue(material_id, out path);
                                materialDict.TryGetValue(material_id, out path);
                                draft = new Draft();
                                draft.start = seg.source_timerange.start;
                                draft.duration = seg.source_timerange.duration;
                                draft.path = path;
                                draft.type = track.type.Equals(DraftType.audio.ToString())
                                    ? DraftType.audio
                                    : DraftType.video;
                                draft.index = segIndex;
                                draft.trackIndex = trackIndex;
                                drafts.Add(draft);
                            }
                            segIndex++;
                        }
                    }
                    if (!Directory.Exists(AppConfig.Instance.JianYingOutPath + "\\" + project))
                    {
                        Directory.CreateDirectory(
                            AppConfig.Instance.JianYingOutPath + "\\" + project
                        );
                    }
                    double st = draft.start;
                    double et = draft.duration;
                    TimeSpan start = TimeSpan.FromMilliseconds(st / 1000);
                    TimeSpan end = TimeSpan.FromMilliseconds(et / 1000);
                    //ffmpeg -ss 00:08:00.0333330 -t 00:06:00.1666660 -i "D:/影视/甄嬛传/甄嬛传.E10.mp4"
                    //-q:a 0 -map a -y "C:\Users\mcncl\Desktop\0.wav"
                    FileInfo f = new FileInfo(draft.path);
                    Process process = new Process();
                    process.StartInfo.FileName = "ffmpeg";
                    process.StartInfo.WorkingDirectory = f.DirectoryName;
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    string num = draft.trackIndex + "_" + draft.index;
                    string outFile =
                        AppConfig.Instance.JianYingOutPath
                        + "\\"
                        + project
                        + "\\"
                        + project
                        + "_"
                        + num
                        + (isVideo ? ".mp4" : ".wav");
                    string param = "-ss " + start.ToString();
                    param += " -t " + end.ToString();
                    param += " -i \"" + draft.path + "\"";
                    param += " -vn -y \"" + outFile + "\"";
                    string outPath = AppConfig.Instance.JianYingOutPath + "\\" + project;
                    if (isVideo)
                    {
                        param = "-ss " + start.ToString();
                        param += " -t " + end.ToString();
                        param += "  -i \"" + draft.path + "\"";
                        param += " -c copy ";
                        param += "  -y \"" + outFile + "\"";
                    }

                    process.StartInfo.Arguments = param;
                    process.StartInfo.CreateNoWindow = true; //显示命令行窗口
                    //不使用操作系统使用的shell启动进程
                    process.StartInfo.UseShellExecute = false;
                    //将输出信息重定向
                    process.StartInfo.RedirectStandardInput = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.EnableRaisingEvents = true;

                    process.OutputDataReceived += (o, e) =>
                        Debug.WriteLine(e.Data ?? "NULL", "jianying");
                    process.ErrorDataReceived += (o, e) =>
                        Debug.WriteLine(e.Data ?? "NULL", "jianying");
                    process.Exited += (o, e) => Debug.WriteLine("Exited", "jianying");

                    process.Start();
                    //开始异步读取输出
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    System.Diagnostics.Process.Start(
                        "Explorer",
                        AppConfig.Instance.JianYingOutPath + "\\" + project
                    );
                })
            );
        public ICommand ExportJianYingAudioOrVideoCommand =>
            _ExportJianYingAudioOrVideoCommand
            ?? (
                _ExportJianYingAudioOrVideoCommand = new RelayCommand<object>(o =>
                {
                    string p = (string)o;
                    bool isVideo = p.StartsWith("视频__");
                    string project = p.Replace("视频__", "");
                    string content = File.ReadAllText(
                        AppConfig.Instance.JianYingDraftPath
                            + "\\"
                            + project
                            + "\\draft_content.json"
                    );
                    JianYingDraft jydraft = JsonConvert.DeserializeObject<JianYingDraft>(content);
                    Dictionary<string, string> materialDict = new Dictionary<string, string>();
                    foreach (Video v in jydraft.materials.videos)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    foreach (vo.Audio v in jydraft.materials.audios)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    List<Draft> drafts = new List<Draft>();
                    int trackIndex = 0;
                    foreach (vo.Track track in jydraft.tracks)
                    {
                        trackIndex++;
                        if (!track.type.Equals("video") && !track.type.Equals("audio"))
                        {
                            continue;
                        }
                        if (track.type.Equals("audio") && isVideo)
                        {
                            continue;
                        }
                        int segIndex = 0;
                        foreach (Segment seg in track.segments)
                        {
                            string material_id = seg.material_id;
                            string path = null;
                            materialDict.TryGetValue(material_id, out path);
                            materialDict.TryGetValue(material_id, out path);
                            Draft draft = new Draft();
                            draft.start = seg.source_timerange.start;
                            draft.duration = seg.source_timerange.duration;
                            draft.path = path;
                            draft.type = track.type.Equals(DraftType.audio.ToString())
                                ? DraftType.audio
                                : DraftType.video;
                            draft.index = segIndex;
                            draft.trackIndex = trackIndex;
                            drafts.Add(draft);
                            segIndex++;
                        }
                    }
                    for (int i = 0; i < drafts.Count; i++)
                    {
                        if (!Directory.Exists(AppConfig.Instance.JianYingOutPath + "\\" + project))
                        {
                            Directory.CreateDirectory(
                                AppConfig.Instance.JianYingOutPath + "\\" + project
                            );
                        }
                        Draft draft = drafts[i];
                        double st = draft.start;
                        double et = draft.duration;
                        TimeSpan start = TimeSpan.FromMilliseconds(st / 1000);
                        TimeSpan end = TimeSpan.FromMilliseconds(et / 1000);
                        //ffmpeg -ss 00:08:00.0333330 -t 00:06:00.1666660 -i "D:/影视/甄嬛传/甄嬛传.E10.mp4"
                        //-q:a 0 -map a -y "C:\Users\mcncl\Desktop\0.wav"
                        FileInfo f = new FileInfo(draft.path);
                        Process process = new Process();
                        process.StartInfo.FileName = "ffmpeg";
                        process.StartInfo.WorkingDirectory = f.DirectoryName;
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        string num = "000" + i.ToString();
                        if (drafts.Count >= 100)
                        {
                            num = num.Substring(num.Length - 3);
                        }
                        else if (drafts.Count >= 10)
                        {
                            num = num.Substring(num.Length - 2);
                        }
                        else
                        {
                            num = num.Substring(num.Length - 1);
                        }
                        string outFile =
                            AppConfig.Instance.JianYingOutPath
                            + "\\"
                            + project
                            + "\\"
                            + project
                            + "_"
                            + num
                            + ".wav";
                        string param = "-ss " + start.ToString();
                        param += " -t " + end.ToString();
                        param += " -i \"" + draft.path + "\"";
                        FileInfo srcFile = new FileInfo(draft.path);
                        string srcFileName = srcFile.Name;
                        param += " -vn -y \"" + outFile + "\"";
                        string outPath = AppConfig.Instance.JianYingOutPath + "\\" + project;
                        if (isVideo)
                        {
                            outFile =
                                AppConfig.Instance.JianYingOutPath
                                + "\\"
                                + project
                                + "\\"
                                + srcFileName;
                            param = "-ss " + start.ToString();
                            param += " -t " + end.ToString();
                            param += "  -i \"" + draft.path + "\"";
                            param += " -c copy ";
                            param += "  -y \"" + outFile + "\"";
                        }

                        process.StartInfo.Arguments = param;
                        process.StartInfo.CreateNoWindow = true; //显示命令行窗口
                        //不使用操作系统使用的shell启动进程
                        process.StartInfo.UseShellExecute = false;
                        //将输出信息重定向
                        process.StartInfo.RedirectStandardInput = true;
                        process.StartInfo.RedirectStandardOutput = true;
                        process.StartInfo.RedirectStandardError = true;
                        process.EnableRaisingEvents = true;

                        process.OutputDataReceived += (o, e) =>
                            Debug.WriteLine(e.Data ?? "NULL", "jianying");
                        process.ErrorDataReceived += (o, e) =>
                            Debug.WriteLine(e.Data ?? "NULL", "jianying");
                        process.Exited += (o, e) => Debug.WriteLine("Exited", "jianying");

                        process.Start();
                        //开始异步读取输出
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                    }
                    System.Diagnostics.Process.Start(
                        "Explorer",
                        AppConfig.Instance.JianYingOutPath + "\\" + project
                    );
                    var content1 = new NotificationContent()
                    {
                        Title = "成功导出剪映项目",
                        Type = NotificationType.Information,
                        Message = project,
                    };
                    AppManager.Instance.NotificationManager.Show(content1);
                })
            );
        public ICommand ExportJianYingVideoRenameCommand =>
            _ExportJianYingVideoRenameCommand
            ?? (
                _ExportJianYingVideoRenameCommand = new RelayCommand<object>(o =>
                {
                    string project = (string)o;
                    string content = File.ReadAllText(
                        AppConfig.Instance.JianYingDraftPath
                            + "\\"
                            + project
                            + "\\draft_content.json"
                    );
                    JianYingDraft jydraft = JsonConvert.DeserializeObject<JianYingDraft>(content);
                    Dictionary<string, string> materialDict = new Dictionary<string, string>();
                    foreach (Video v in jydraft.materials.videos)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    foreach (vo.Audio v in jydraft.materials.audios)
                    {
                        materialDict.Add(v.id, v.path);
                    }
                    List<Draft> drafts = new List<Draft>();
                    int trackIndex = 0;
                    foreach (vo.Track track in jydraft.tracks)
                    {
                        trackIndex++;
                        if (!track.type.Equals("video") && !track.type.Equals("audio"))
                        {
                            continue;
                        }
                        int segIndex = 0;
                        foreach (Segment seg in track.segments)
                        {
                            string material_id = seg.material_id;
                            string path = null;
                            materialDict.TryGetValue(material_id, out path);
                            materialDict.TryGetValue(material_id, out path);
                            Draft draft = new Draft();
                            draft.start = seg.source_timerange.start;
                            draft.duration = seg.source_timerange.duration;
                            draft.path = path;
                            draft.type = track.type.Equals(DraftType.audio.ToString())
                                ? DraftType.audio
                                : DraftType.video;
                            draft.index = segIndex;
                            draft.trackIndex = trackIndex;
                            drafts.Add(draft);
                            segIndex++;
                        }
                    }
                    for (int i = 0; i < drafts.Count; i++)
                    {
                        if (!Directory.Exists(AppConfig.Instance.JianYingOutPath + "\\" + project))
                        {
                            Directory.CreateDirectory(
                                AppConfig.Instance.JianYingOutPath + "\\" + project
                            );
                        }
                        Draft draft = drafts[i];
                        double st = draft.start;
                        double et = draft.duration;
                        TimeSpan start = TimeSpan.FromMilliseconds(st / 1000);
                        TimeSpan end = TimeSpan.FromMilliseconds(et / 1000);
                        //ffmpeg -ss 00:08:00.0333330 -t 00:06:00.1666660 -i "D:/影视/甄嬛传/甄嬛传.E10.mp4"
                        //-q:a 0 -map a -y "C:\Users\mcncl\Desktop\0.wav"
                        // Log.Debug("runTask,添加任务" + (i + 1) + "轨道 " + draft.trackIndex + " 草稿 " + draft.index);
                        FileInfo f = new FileInfo(draft.path);
                        Process process = new Process();
                        process.StartInfo.FileName = "ffmpeg";
                        process.StartInfo.WorkingDirectory = f.DirectoryName;
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        string num = "000" + i.ToString();
                        if (drafts.Count >= 100)
                        {
                            num = num.Substring(num.Length - 3);
                        }
                        else if (drafts.Count >= 10)
                        {
                            num = num.Substring(num.Length - 2);
                        }
                        else
                        {
                            num = num.Substring(num.Length - 1);
                        }
                        string param = "";
                        FileInfo srcFile = new FileInfo(draft.path);
                        string srcFileName = srcFile.Name;
                        string outFile =
                            AppConfig.Instance.JianYingOutPath
                            + "\\"
                            + project
                            + "\\"
                            + draft.trackIndex
                            + "-"
                            + draft.index
                            + ".mp4";
                        param = "-ss " + start.ToString();
                        param += " -t " + end.ToString();
                        param += "  -i \"" + draft.path + "\"";
                        param +=
                            "  -c:v h264_nvenc -gpu 0 -pix_fmt yuv420p -color_range pc -color_trc bt709 -color_primaries bt709 -colorspace bt709 ";
                        param += " -c:a aac ";
                        param += "  -y \"" + outFile + "\"";

                        process.StartInfo.Arguments = param;
                        process.StartInfo.CreateNoWindow = true; //显示命令行窗口
                        //不使用操作系统使用的shell启动进程
                        process.StartInfo.UseShellExecute = false;
                        //将输出信息重定向
                        process.StartInfo.RedirectStandardInput = true;
                        process.StartInfo.RedirectStandardOutput = true;
                        process.StartInfo.RedirectStandardError = true;
                        process.EnableRaisingEvents = true;

                        process.OutputDataReceived += (o, e) =>
                            Debug.WriteLine(e.Data ?? "NULL", "jianying");
                        process.ErrorDataReceived += (o, e) =>
                            Debug.WriteLine(e.Data ?? "NULL", "jianying");
                        process.Exited += (o, e) => Debug.WriteLine("Exited", "jianying");

                        process.Start();
                        //开始异步读取输出
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                        process.WaitForExit();
                    }
                    System.Diagnostics.Process.Start(
                        "Explorer",
                        AppConfig.Instance.JianYingOutPath + "\\" + project
                    );
                    var content2 = new NotificationContent()
                    {
                        Title = "视频片段已导出",
                        Type = NotificationType.Information,
                    };
                    AppManager.Instance.NotificationManager.Show(content2);
                })
            );
        public ICommand ConfigJianYingDraftCommand =>
            _ConfigJianYingDraftCommand
            ?? (
                _ConfigJianYingDraftCommand = new RelayCommand<object>(o =>
                {
                    string jianYingDraftPath = AppConfig.Instance.JianYingDraftPath;
                    if (string.IsNullOrEmpty(jianYingDraftPath))
                    {
                        System.Windows.MessageBox.Show("未设置剪映草稿目录，请设置");
                    }
                    var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderBrowserDialog.UseDescriptionForTitle = true;
                    folderBrowserDialog.Description = "请选择剪映草稿目录";
                    if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        AppConfig.Instance.JianYingDraftPath = folderBrowserDialog.SelectedPath;
                        AppConfig.Instance.Save();
                    }
                })
            );

        public ICommand ConfigJianYingOutCommand =>
            _ConfigJianYingOutCommand
            ?? (
                _ConfigJianYingOutCommand = new RelayCommand<object>(o =>
                {
                    string jianYingOutPath = AppConfig.Instance.JianYingOutPath;

                    if (string.IsNullOrEmpty(jianYingOutPath))
                    {
                        System.Windows.MessageBox.Show("未设置导出目录，请设置");
                    }

                    var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderBrowserDialog.Description = "请选择导出目录";
                    folderBrowserDialog.UseDescriptionForTitle = true;
                    if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        AppConfig.Instance.JianYingOutPath = folderBrowserDialog.SelectedPath;
                        AppConfig.Instance.Save();
                    }
                })
            );
        public ICommand OpenJianYingOutPathCommand =>
            _OpenJianYingOutPathCommand
            ?? (
                _OpenJianYingOutPathCommand = new RelayCommand<object>(o =>
                {
                    string jianYingOutPath = AppConfig.Instance.JianYingOutPath;
                    if (!string.IsNullOrEmpty(jianYingOutPath))
                    {
                        System.Diagnostics.Process.Start("Explorer", jianYingOutPath);
                    }
                    else
                    {
                        ConfigJianYingOutCommand.ExecuteIfCan();
                    }
                })
            );
        public ICommand OpenJianYingDraftPathCommand =>
            _OpenJianYingDraftPathCommand
            ?? (
                _OpenJianYingDraftPathCommand = new RelayCommand<object>(o =>
                {
                    string jianYingDraftPath = AppConfig.Instance.JianYingDraftPath;
                    if (!string.IsNullOrEmpty(jianYingDraftPath))
                    {
                        System.Diagnostics.Process.Start("Explorer", jianYingDraftPath);
                    }
                    else
                    {
                        ConfigJianYingDraftCommand.ExecuteIfCan();
                    }
                })
            );
        public ICommand ChangeBackgroundCommand =>
            _ChangeBackgroundCommand
            ?? (
                _ChangeBackgroundCommand = new RelayCommand<object>(o =>
                {
                    var brushConverter = new BrushConverter();
                    SolidColorBrush background = (SolidColorBrush)
                        brushConverter.ConvertFromString((string)o);
                    AppConfig.Instance.BackgroundColor = (string)o;
                    AppManager.Instance.BackgroundColor = background;
                    AppConfig.Instance.Save();
                })
            );
        public ICommand ChangeAccentColorCommand =>
            _ChangeAccentColorCommand
            ?? (
                _ChangeAccentColorCommand = new RelayCommand<object>(o =>
                {
                    string name = o as string;
                    if (string.IsNullOrEmpty(name))
                    {
                        return;
                    }
                    ThemeManager.Current.ChangeThemeColorScheme(
                        System.Windows.Application.Current,
                        name
                    );
                    InitThemeColor();
                    AppConfig.Instance.AccentName = name;
                    AppConfig.Instance.Save();
                })
            );
        public ICommand JianYingHelpCommand =>
            _JianYingHelpCommand
            ?? (
                _JianYingHelpCommand = new RelayCommand<object>(o =>
                {
                    System.Windows.MessageBox.Show("只支持剪映专业版版本6.0.0以下", "支持版本信息");
                })
            );
        public ICommand ShowMenuCommand =>
            _ShowMenuCommand
            ?? (
                _ShowMenuCommand = new RelayCommand<object>(o =>
                {
                    if (o is System.Windows.Controls.Button button)
                    {
                        if (button.ContextMenu != null)
                        {
                            button.ContextMenu.PlacementTarget = button;
                            button.ContextMenu.Placement = PlacementMode.Bottom;
                            button.ContextMenu.IsOpen = true;
                        }
                    }
                    else if (o is Popup popup)
                    {
                        popup.IsOpen = true;
                    }
                })
            );

        public ICommand OpenGitAddressCommand =>
            _OpenGitAddressCommand
            ?? (
                _OpenGitAddressCommand = new RelayCommand<object>(o =>
                {
                    string[] infos = ProjectInfo.Instance.remoteUrl.Split(" ");
                    Util.Utils.OpenUrlUsingEdge(infos[1]);
                })
            );

        public ICommand ShowPageCommand =>
            _ShowPageCommand
            ?? (
                _ShowPageCommand = new RelayCommand<object>(o =>
                {
                    MenuVo vo = (MenuVo)o;
                    MainWindow.Instance.Title = "视频处理工具 -- " + vo.Name;
                    string path = vo.Path;
                    MainWindow
                        .Instance.MainWindowFrame()
                        .Navigate(new Uri(path, UriKind.RelativeOrAbsolute));
                })
            );

        public ICommand SetDefaultPageCommand =>
            _SetDefaultPageCommand
            ?? (
                _SetDefaultPageCommand = new RelayCommand<object>(o =>
                {
                    Frame frame = MainWindow.Instance.MainWindowFrame();
                    Uri source = frame.Source;
                    string path = "/" + source.OriginalString;
                    AppConfig.Instance.DefaultPage = path;
                    AppConfig.Instance.DefaultTitle = MainWindow.Instance.Title;
                    AppConfig.Instance.Save();
                    var content = new NotificationContent()
                    {
                        Title = "已设置启动页面为",
                        Type = NotificationType.Success,
                        Message = AppConfig.Instance.DefaultTitle.Replace("视频处理工具 -- ", ""),
                    };
                    AppManager.Instance.NotificationManager.Show(
                        content,
                        expirationTime: TimeSpan.FromSeconds(3)
                    );
                })
            );
    }
}
